<?php

define('DATA_TABLE_NAME','news');
/**************** ACTION HANDER BEGIN *********************/
//修改数据
function save_block()
{
	$oldRow = false;
	if(isset($_REQUEST['id']) && intval($_REQUEST['id']) > 0)
		$oldRow = fetch_row_data($_REQUEST['id'],$error);
	
	//$image_path_list = upload_image_and_generate_thumbnail($_REQUEST['lb'],$_REQUEST['BigClassName'],$oldRow);
	$image_path_list = only_generate_thumbnail($_REQUEST['lb'],$_REQUEST['BigClassName'],$oldRow);
	if(isset($_REQUEST['id']) && intval($_REQUEST['id']) > 0)
	{
		//update 
			$query = "update `".constant('DATA_TABLE_NAME')."` SET ".compose_sql_from_request($image_path_list).",`edittime`=now(),".sprintf("`editname`='%s' WHERE `id`=%d",$_SESSION['username2'],$_REQUEST['id']);
	}else{
		//insert
		$query = "INSERT INTO `".constant('DATA_TABLE_NAME')."` SET ".compose_sql_from_request($image_path_list).",`addtime`=now(),`edittime`=now()";
	}
	$result=mysql_query($query);
	if($result == false)
		exit(sprintf("%s%s%s",mysql_error(),__FILE__,__LINE__));
	//update statistic records
	update_statistic_articles_number();
	delete_garbage_files_in_tmp_dir();
	return $result !== false;
}
//delete images
function del_images_block()
{
	
	$id = $_REQUEST['id'];
	$imgField = $_REQUEST['imgField'];
	unlink_article_image($id,$imgField);
}
//set status
function set_status_block()
{

	$id = $_REQUEST['id'];
	$is_ok = $_REQUEST['status'];
	if($is_ok == '1')
	{
			$query = sprintf("UPDATE `%s` SET `isok`='%s',`senttime`=now() WHERE `id`=%d",constant('DATA_TABLE_NAME'),mysql_real_escape_string($is_ok),$id);

	}else{
			$query = sprintf("UPDATE `%s` SET `isok`='%s' WHERE `id`=%d",constant('DATA_TABLE_NAME'),mysql_real_escape_string($is_ok),$id);

	}
	$result=mysql_query($query);
	if($result == false)
		exit(sprintf("%s%s%s",mysql_error(),__FILE__,__LINE__));
	//update statistic records
	update_statistic_articles_number();
	return $result !== false;
}
// delete action
function delete_row_block()
{
	$id = $_REQUEST['id'];
	unlink_article_all_image($id);
	$query = sprintf("DELETE FROM `%s` WHERE `id`=%d",constant('DATA_TABLE_NAME'),$id);
	$result=mysql_query($query);
	if($result == false)
		exit(sprintf("%s%s%s",mysql_error(),__FILE__,__LINE__));
	//update statistic records
	update_statistic_articles_number();
}
/**************** ACTION HANDER END *********************/

function compose_sql_from_request($image_path_list)
{
	$sql_field = '';
	//content
	switch($_REQUEST['lb'])
	{
		case '1':
		case '4':
			$sql_field .= sprintf("`content`='%s',",addslashes($_REQUEST['content1']));
		break;
		case '2':
			$sql_field .= sprintf("`content`='%s',",addslashes($_REQUEST['content2']));
		break;
		case '3':
			$sql_field .= sprintf("`content`='%s',",addslashes($_REQUEST['content4']));
		break;
		default:
			$sql_field .= "`content`='',";
		break;
	}
	$sql_field .= sprintf("`title`='%s',",mysql_real_escape_string($_REQUEST['title']));
	$sql_field .= sprintf("`BigClassName`='%s',",mysql_real_escape_string($_REQUEST['BigClassName']));
	$sql_field .= sprintf("`BigClassName2`='%s',",mysql_real_escape_string($_REQUEST['BigClassName2']));
	$sql_field .= sprintf("`addname`='%s',",mysql_real_escape_string($_REQUEST['addname']));
	$sql_field .= sprintf("`addnamedisplay`='%s',",mysql_real_escape_string(get_autho_name_by_loginname($_REQUEST['addname'])));
	$sql_field .= sprintf("`lb`='%s',",mysql_real_escape_string($_REQUEST['lb']));
	$sql_field .= sprintf("`tagcloud1`='%s',",mysql_real_escape_string($_REQUEST['tagcloud1']));
	$sql_field .= sprintf("`tagcloud2`='%s',",mysql_real_escape_string($_REQUEST['tagcloud2']));
	$sql_field .= sprintf("`tagcloud3`='%s',",mysql_real_escape_string($_REQUEST['tagcloud3']));
	$sql_field .= sprintf("`tagcloud4`='%s',",mysql_real_escape_string($_REQUEST['tagcloud4']));
	$sql_field .= sprintf("`tagcloud5`='%s',",mysql_real_escape_string($_REQUEST['tagcloud5']));
	$sql_field .= sprintf("`isok`='%s',",mysql_real_escape_string($_REQUEST['isok']));
	
	if(isset($_REQUEST['lock']))
	{
		$lock = 'Y';
		$sql_field .= sprintf("`lock_start`='%s',",mysql_real_escape_string($_REQUEST['lock_start']));
		$sql_field .= sprintf("`lock_end`='%s',",mysql_real_escape_string($_REQUEST['lock_end']));
	}else{
		$lock = '';
	}
	$sql_field .= "`lock`='$lock',";
	if(isset($_REQUEST['lock2']))
	{
		$lock2 = 'Y';
	}else{
		$lock2 = '';
	}
	$sql_field .= "`lock2`='$lock2',";
	//images descripton
	for($i=1;$i<16;$i++)
	{
		$image_desc = $_REQUEST['images'.$i.'_desc'];
		$image_desc = mysql_real_escape_string($image_desc);
		$sql_field .= "`images".$i."_desc`='$image_desc',";
	}
	for($i=1;$i<16;$i++)
	{
		
		if(isset($_REQUEST["extraread_$i"]))
			$sql_field .= "`c$i`='1',";
		else
			$sql_field .= "`c$i`='0',";
	}
	if($image_path_list && is_array($image_path_list) && count($image_path_list) > 0)
	{
		foreach($image_path_list as $i=>$path)
		{
			$sql_field .= sprintf("`images%d`='%s',",$i,$path);
		}
	}
	$sql_field  = substr($sql_field,0,-1);
	
	return $sql_field;
}
function check_article_lockable($BigClassName,$BigClassName2 = '',$current_id)
{
	$canlock = true;
	if($BigClassName == 'Feature')
	{
		if(intval($current_id) == 0)
			$sql = sprintf("SELECT count(1) AS `co` FROM `news` WHERE `BigClassName`='%s' AND `BigClassName2`='%s' AND `lock`='Y'",mysql_real_escape_string($BigClassName),mysql_real_escape_string($BigClassName2));
		else
			$sql = sprintf("SELECT count(1) AS `co` FROM `news` WHERE `BigClassName`='%s' AND `BigClassName2`='%s' AND `lock`='Y' AND `id` != %d",mysql_real_escape_string($BigClassName),mysql_real_escape_string($BigClassName2),$current_id);
	
		$result=mysql_query($sql);
		if($result == false)
		{
			$error = sprintf("%s%s%s",mysql_error(),__FILE__,__LINE__);
			return false; 
		}
		$info =mysql_fetch_assoc($result);
		if($info['co'] > 4)
		{
			$canlock = false;
		}
	}else if($BigClassName == 'News')
	{
		if($BigClassName2 == '')
		{
			if(intval($current_id) == 0)
				$sql = sprintf("SELECT count(1) AS `co` FROM `news` WHERE  `BigClassName`='%s' AND `lock2`='Y'",mysql_real_escape_string($BigClassName));
			else
				$sql = sprintf("SELECT count(1) AS `co` FROM `news` WHERE  `BigClassName`='%s' AND `lock2`='Y' AND `id` != %d",mysql_real_escape_string($BigClassName),$current_id);
	
			$result=mysql_query($sql);
			if($result == false)
			{
				$error = sprintf("%s%s%s",mysql_error(),__FILE__,__LINE__);
				return false; 
			}
			$info =mysql_fetch_assoc($result);
			if($info['co'] > 4)
			{
				$canlock = false;
			}
		}else{
			if(intval($current_id) == 0)
				$sql = sprintf("SELECT count(1) AS `co` FROM `news` WHERE `BigClassName`='%s' AND `BigClassName2`='%s' AND `lock`='Y'",mysql_real_escape_string($BigClassName),mysql_real_escape_string($BigClassName2));
			else
				$sql = sprintf("SELECT count(1) AS `co` FROM `news` WHERE `BigClassName`='%s' AND `BigClassName2`='%s' AND `lock`='Y' AND `id` != %d",mysql_real_escape_string($BigClassName),mysql_real_escape_string($BigClassName2),$current_id);
	
			$result=mysql_query($sql);
			if($result == false)
			{
				$error = sprintf("%s%s%s",mysql_error(),__FILE__,__LINE__);
				return false; 
			}
			$info =mysql_fetch_assoc($result);
			if($info['co'] > 4)
			{
				$canlock = false;
			}
		}
	}else if($BigClassName == 'Column' || $BigClassName == 'Event')
	{
		if(intval($current_id) == 0)
			$sql = sprintf("SELECT count(1) AS `co` FROM `news` WHERE `BigClassName`='%s' AND `lock`='Y'",mysql_real_escape_string($BigClassName));
		else
			$sql = sprintf("SELECT count(1) AS `co` FROM `news` WHERE `BigClassName`='%s' AND `lock`='Y' AND `id` != %d",mysql_real_escape_string($BigClassName),$current_id);
	
		$result=mysql_query($sql);
		if($result == false)
		{
			$error = sprintf("%s%s%s",mysql_error(),__FILE__,__LINE__);
			return false; 
		}
		$info =mysql_fetch_assoc($result);
		if($info['co'] > 4)
		{
			$canlock = false;
		}
	}
	return $canlock;
}
function fetch_row_data($id,&$error)
{
	$info = array();
 	$id=make_safe($id);	 
  $sql= sprintf("select * from `%s` where `id`=%d",constant('DATA_TABLE_NAME'),$id);	

	$result=mysql_query($sql);
	if($result == false)
	{
		$error = sprintf("%s%s%s",mysql_error(),__FILE__,__LINE__);
		return false; 
	}

	$info =mysql_fetch_assoc($result);
	if($info === false)
	{
		$error = "Request data not found";
		return false;
	}
	$error = '';
	return $info;
}



function unlink_article_image($articleID,$imageField)
{
	$query = sprintf("SELECT `%s` AS `fileID` FROM `%s` WHERE `id`=%d",mysql_real_escape_string($imageField),constant('DATA_TABLE_NAME'),$articleID);
	$result=mysql_query($query);
	if($result == false)
		exit(sprintf("%s%s%s",mysql_error(),__FILE__,__LINE__));
	
	if(($row = mysql_fetch_assoc($result)))
	{
		$file_id = $row['fileID'];
		if(strlen($file_id) == 0 )
			return;
		unlink_article_image_on_disk($file_id);
	}
	
	$query = sprintf("UPDATE `%s` SET `%s`='' WHERE `id`=%d",constant('DATA_TABLE_NAME'),mysql_real_escape_string($imageField),$articleID);
	$result=mysql_query($query);
	if($result == false)
		exit(sprintf("%s%s%s",mysql_error(),__FILE__,__LINE__));
}
function unlink_article_all_image($articleID)
{
	$query = "SELECT ";
	for($i=1;$i<16;$i++)
	{
		$query .= "`images$i`,";
	}
	$query = substr($query,0,-1);
	$query .= sprintf(" FROM `%s` WHERE `id`=%d",constant('DATA_TABLE_NAME'),$articleID);
	$result=mysql_query($query);
	if($result == false)
		exit(sprintf("%s%s%s",mysql_error(),__FILE__,__LINE__));
	
	if(($row = mysql_fetch_assoc($result)))
	{
		for($i=1;$i<16;$i++)
		{
			$file_id = $row["images$i"];
			if(strlen($file_id) == 0 )
				continue;
			unlink_article_image_on_disk($file_id);
		}
	}
}

function only_generate_thumbnail($showMode,$catalog,$oldRow)
{
	$image_path_list = array();
	foreach($_REQUEST as $key=>$value)
	{
		preg_match('/^ajaxf_(.*)_images(\d+)$/', $key, $matches);
		if(count($matches) !== 3)
			continue;
		if(strlen($value) == 0)
			continue;
		$img_id = $matches[2];
		if($oldRow)
		 {
		 	unlink_article_image_on_disk($oldRow['images'.$img_id]);
		 }
		 
		 $tmpPath = dirname(dirname(__FILE__)).'/upfiles/tmp/'.$value;
	     $src_img = dirname(dirname(__FILE__)).'/upfiles/'.$value;
	     copy($tmpPath,$src_img);
	     unlink($tmpPath);

		 if(!($catalog == 'Download' && intval($img_id) > 1))
			article_make_thumails($catalog,$src_img,'.jpg',$showMode);
		$image_path_list[$img_id] = basename($value);
	}
	return $image_path_list;
}
function upload_image_and_generate_thumbnail($showMode,$catalog,$oldRow)
{
	$path_prefix = dirname(dirname(__FILE__)).'/upfiles/'.time();
	$file_key_prefix = '';
	switch($showMode)
	{
		case '1'://mix style
		case '4':
		$file_key_prefix  = 'mix';
		break;
		case '2'://horizen style
		$file_key_prefix  = 'hor';
		break;
		case '3'://download style
		$file_key_prefix  = 'dow';
		break;
		default:
		return;
	}
	$image_path_list = array();
	for($i=1;$i<16;$i++)
	{
		$image_id = $file_key_prefix."_images$i";
		if(!array_key_exists($image_id,$_FILES) || !array_key_exists('tmp_name',$_FILES[$image_id]) || strlen($_FILES[$image_id]['tmp_name']) == 0)
			continue;
		$file_type = strstr($_FILES[$image_id]['name'],'.');
		if(!($file_type==".jpg"  or $file_type==".jpge" or $file_type==".gif"  or $file_type==".bmp"))
		 continue;
		 //delete the old image
		 if($oldRow)
		 {
		 	unlink_article_image_on_disk($oldRow['images'.$i]);
		 }
		$src_path = $path_prefix.'-'.$i.$file_type;
		move_uploaded_file($_FILES[$image_id]['tmp_name'],$src_path);
		//Download image only thumnai the first image
		if(!($catalog == 'Download' && $i > 1))
			article_make_thumails($catalog,$src_path,'.jpg',$showMode);
		$image_path_list[$i] = basename($src_path);
	}
	
	return $image_path_list;
}
function unlink_article_image_on_disk($file_id )
{
		if(strlen($file_id) == 0 )
			return;
		$current_dir = dirname(dirname(__FILE__)).'/upfiles/';
		
		@unlink($current_dir.$file_id);
		@unlink($current_dir.$file_id.'-431x253.jpg');
		@unlink($current_dir.$file_id.'-x125.jpg');
		@unlink($current_dir.$file_id.'-x400.jpg');
		@unlink($current_dir.$file_id.'-35x35.jpg');
		@unlink($current_dir.$file_id.'-x490.jpg');
	
		@unlink($current_dir.$file_id.'-400x.jpg');
		@unlink($current_dir.$file_id.'-x400.jpg');
		@unlink($current_dir.$file_id.'-169x.jpg');
		@unlink($current_dir.$file_id.'-276x.jpg');
		@unlink($current_dir.$file_id.'-x890.jpg');
		
}
function article_make_thumails($catalog,$srcImage,$file_type,$showMode)
{
		
		
		//Make -169x
		$desc = $srcImage.'-x125'.$file_type;
		//make_thumnail($srcImage,$desc ,false,125,1);
		
		$desc = $srcImage.'-x125'.$file_type;
		//make_thumnail($srcImage,$desc ,431,253,4);
		$helper = new ImageThumnailHelper_Crop();
		$helper->auto_crop($srcImage,$desc ,169,125);
		
	if($catalog == 'Feature')
	{
		//Make feature.php 431X
		//source image size 600X400
		$desc = $srcImage.'-431x253'.$file_type;
		//make_thumnail($srcImage,$desc ,431,253,4);
		$helper = new ImageThumnailHelper_Crop();
		$helper->auto_crop($srcImage,$desc ,431,253);
		switch($showMode)
		{
			case '1':
			case '4':
					
				//Make x400
				//$desc = $srcImage.'-x400'.$file_type;
				//make_thumnail($srcImage,$desc ,false,400,1);
				//Make 35x35 fixed width then cut height
				$desc = $srcImage.'-35x35'.$file_type;
				make_thumnail($srcImage,$desc ,35,35,4);
			break;
			case '2':
				//Make x490 fixed height then cut width
				//$desc = $srcImage.'-x490'.$file_type;
				//make_thumnail($srcImage,$desc ,false,490,1);
				//Make 35x35 fixed width then cut height
				$desc = $srcImage.'-35x35'.$file_type;
				make_thumnail($srcImage,$desc ,35,35,4);
			break;
			case '3':
				//Make x490 fixed height then cut width
				$desc = $srcImage.'-x490'.$file_type;
				make_thumnail($srcImage,$desc ,false,490,1);
			break;
		}
		
	}else if($catalog == 'Column' || $catalog == 'News' || $catalog == 'Event')
	{
		//Make flash -400x
		$desc = $srcImage.'-400x'.$file_type;
		make_thumnail($srcImage,$desc ,400,false);
		//Make -x400
		$desc = $srcImage.'-x400'.$file_type;
		make_thumnail($srcImage,$desc ,false,400,1);
		//Make -169x
		$desc = $srcImage.'-169x'.$file_type;
		make_thumnail($srcImage,$desc ,169,false);
		
		
		//Make 35x35 fixed width then cut height
		$desc = $srcImage.'-35x35'.$file_type;
		make_thumnail($srcImage,$desc ,35,35,4);
		//Make 35x35 fixed height then cut width
		//$desc = $srcImage.'-35x35'.$file_type;
		//make_thumnail($srcImage,$desc ,35,35,3);

	}else if($catalog == 'Download')
	{
		//Make flash -276x
		$desc = $srcImage.'-276x'.$file_type;
		make_thumnail($srcImage,$desc ,276,false);
		//Make flash -890
		$desc = $srcImage.'-x890'.$file_type;
		make_thumnail($srcImage,$desc ,false,890,1);
	}	
}

/**
/*$mode
			0 : Fixed width auto height
			1 : Fixed height auto with
			2 : Fixe width then cut height
			3 : Fixed height then cut with
*/
function make_thumnail($src,$des,$width,$height,$mode = 0)
{
	switch($mode)
	{
		case '0':
		$helper = new ImageThumnailHelper_FixWidthAutoHeight();
		break;
		case '1':
		$helper = new ImageThumnailHelper_FixHeightAutoWidth();
		break;
		case '2':
		$helper = new ImageThumnailHelper_FixWidthAutoHeight_cutHeight();
		break;
		case '3':
		$helper = new ImageThumnailHelper_FixHeightAutoWidth_cutWidth();
		break;
		case '4':
		$helper = new ImageThumnailHelper_Auto();
		break;
	}
  $helper->resizeimage($src,$des,$width,$height);
}

?>